<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use App\Exception\XZXValidationException;
use App\Service\TradeOrderForceSuccessService;
use App\Service\TradeOrderReviewService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use App\Utils\FileUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Arr;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use App\Middleware\AdminApi\NodeAccessMiddleware;

/**
 * Class TradeOrderForceSuccessController
 *
 * @package App\Controller
 * @Controller(prefix="/admin/api/tradeOrderForceSuccess")
 */
class TradeOrderForceSuccessController extends AdminBaseController {
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var TradeOrderForceSuccessService
     */
    protected $TradeOrderForceSuccessService;

    /**
     * @Inject()
     * @var TradeOrderReviewService
     */
    protected $TradeOrderReviewService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct (LoggerFactory $loggerFactory) {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get (RequestInterface $request) {
        $validator = $this->validationFactory->make($request->all(), [
            'id' => 'required|uuid',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        // $ext = $this->request->getAttribute("ext");
        // $param['isSuperRole'] =  $ext['isSuperRole'];
        // if(!$param['isSuperRole']){
        //     $param['mchIdList'] =  $ext['mchIdList'];
        // }
        // $param['source'] = 2;
        return $this->TradeOrderForceSuccessService->get($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     */
    public function add (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'uploadFile' => 'required|url',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext   = $this->request->getAttribute("ext");
        // $param['isSuperRole'] =  $ext['isSuperRole'];
        // if(!$param['isSuperRole']){
        //     $param['mchIdList'] =  $ext['mchIdList'];
        // }
        // $param['source'] = 2;
        $param['createBy'] = $ext['createBy'];
        return $this->TradeOrderForceSuccessService->add($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     */
    public function edit (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'id'         => 'required|uuid',
            'uploadFile' => 'required|url',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        // $ext = $this->request->getAttribute("ext");
        // $param['isSuperRole'] =  $ext['isSuperRole'];
        // if(!$param['isSuperRole']){
        //     $param['mchIdList'] =  $ext['mchIdList'];
        // }
        // $param['source'] = 2;
        return $this->TradeOrderForceSuccessService->edit($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'page'  => 'required|integer|min:1',
            'limit' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext   = $this->request->getAttribute("ext");
        // $param['isSuperRole'] =  $ext['isSuperRole'];
        // if(!$param['isSuperRole']){
        //     $param['mchIdList'] =  $ext['mchIdList'];
        // }
        // $param['source'] = 2;
        if (isset($param['search'])) {
            $search = $param['search'];
            
            CustomUtils::xzxAddSearch($param, $search, 'handleStatus');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if (isset($param["createTimeRange"])) {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }

        return $this->TradeOrderForceSuccessService->list($param);
    }

    /**
     * 初审
     * @PostMapping(path = "handleFirstReview")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     * @throws \Throwable
     */
    public function handleFirstReview (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'tradeNoList' => 'required',
            'isApprove'   => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $ext    = $this->request->getAttribute("ext");
        $params = [
            'tradeNoList' => $request->post('tradeNoList'),
            'isApprove'   => !!$request->post('isApprove'),
            'remark'      => $request->post('remark', ''),
            'reviewLevel' => 1,
        ];

        $params['createBy'] = $ext['createBy'];

        $params['source']      = 2;
        $params['isSuperRole'] = $ext['isSuperRole'];
        if (!$params['isSuperRole']) {
            $params['mchIdList'] = $ext['mchIdList'];
        }

        return $this->TradeOrderReviewService->handleForceSuccessReview($params);
    }

    /**
     * 复审
     * @PostMapping(path = "handleSecondReview")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     * @throws \Throwable
     */
    public function handleSecondReview (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'tradeNoList' => 'required',
            'isApprove'   => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $ext    = $this->request->getAttribute("ext");
        $params = [
            'tradeNoList' => $request->post('tradeNoList'),
            'isApprove'   => !!$request->post('isApprove'),
            'remark'      => $request->post('remark', ''),
            'reviewLevel' => 2,
        ];

        $params['createBy'] = $ext['createBy'];

        $params['source']      = 2;
        $params['isSuperRole'] = $ext['isSuperRole'];
        if (!$params['isSuperRole']) {
            $params['mchIdList'] = $ext['mchIdList'];
        }

        return $this->TradeOrderReviewService->handleForceSuccessReview($params);
    }

    /**
     * 批量补单申请
     * @PostMapping(path = "batchApply")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     * @throws \Throwable
     */
    public function batchApply (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->getUploadedFiles(), [
            'file' => [
                'required',
                'mimes:xls,xlsx',
            ],
        ]);

        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $ext = $this->request->getAttribute("ext", []);

        $file = $request->file('file');

        $path = BASE_PATH.'/runtime/upload/';
        @mkdir($path, 0755, true);

        $filepath = $path.'force-success-'.time().'.'.$file->getExtension();

        $file->moveTo($filepath);

        $param = [
            'filepath' => $filepath,
            'createBy' => Arr::get($ext, 'createBy'),
        ];

        return $this->TradeOrderForceSuccessService->batchApply($param);
    }

    /**
     * 批次初审
     * @PostMapping(path = "handleBatchReviewFirst")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     * @throws \Throwable
     */
    public function handleBatchReviewFirst (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'id'        => 'required',
            'isApprove' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $ext    = $this->request->getAttribute("ext", []);
        $params = [
            'id'        => $request->post('id'),
            'isApprove' => !!$request->post('isApprove'),
            'remark'    => $request->post('remark', ''),
            'createBy'  => Arr::get($ext, 'createBy'),
        ];

        $params['source']      = 2;
        $params['isSuperRole'] = $ext['isSuperRole'];
        if (!$params['isSuperRole']) {
            $params['mchIdList'] = $ext['mchIdList'];
        }

        return $this->TradeOrderForceSuccessService->handleBatchReviewFirst($params);
    }

    /**
     * 批次复审
     * @PostMapping(path = "handleBatchReviewSecond")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     * @throws \Throwable
     */
    public function handleBatchReviewSecond (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), [
            'id'        => 'required',
            'isApprove' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $ext    = $this->request->getAttribute("ext", []);
        $params = [
            'id'        => $request->post('id'),
            'isApprove' => !!$request->post('isApprove'),
            'remark'    => $request->post('remark', ''),
            'createBy'  => Arr::get($ext, 'createBy'),
        ];

        $params['source']      = 2;
        $params['isSuperRole'] = $ext['isSuperRole'];
        if (!$params['isSuperRole']) {
            $params['mchIdList'] = $ext['mchIdList'];
        }

        return $this->TradeOrderForceSuccessService->handleBatchReviewSecond($params);
    }

}
